package com.xzit.rental.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 访问资源出现权限不足，被拒绝
 */
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {

    /*ObjectMapper通常来自于 JSON 处理相关的库（比如 Jackson 等），用于将 Java 对象转换为 JSON 字符串以及进行反向的转换操作，
        在这个类中后续会利用它把要返回的响应信息转换为 JSON 格式发送给客户端。*/
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");

        // 创建响应头对象：HttpHeaders通常用于设置 HTTP 响应的各种头部信息
        HttpHeaders headers = new HttpHeaders();

        // 构建响应实体对象：ResponseEntity是 Spring 框架中用于封装完整 HTTP 响应信息的一个类
        ResponseEntity responseEntity = new ResponseEntity("权限不足！",headers,HttpStatus.FORBIDDEN.value());
        // 将响应实体转换为 JSON 字符串
        String result = objectMapper.writeValueAsString(responseEntity);
        // 向客户端输出响应内容
        response.getWriter().write(result);
    }

}
